﻿using MyX.DSL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LearningEnglish.Models;
using LearningEnglish.ViewModels;
using MyX.Core;

namespace LearningEnglish.LogicDSL
{
    /// <summary>
    /// 一般用户的登录逻辑
    /// </summary>
    public class UserLoginDSL : XIWorkDSL
    {
        public void Init()
        {
            var work = new WorkHelper();

            work.Command<CreateLearnUser>(
                c =>
                {
                    if (LearnUserService.HasForName(c.Name))
                        throw new XMistake(c.ID, "已存在该学习者");

                    var user = new LearnUser(c.Name, c.Password);
                    var token = new Token(user.ID, Token.StaticLiveTime);

                    c.SetResult(user.ID);
                });

            work.Event<LearnUserCreated>(
                e =>
                {
                    var user = new LearnUserRD() { ID = e.XSenderID };

                    var mapper = new XMapper(e, user);
                    mapper.Map();

                    VM.Users.Add(user);
                }, true);

            work.Event<LearnUserCreated>(
                e =>
                {
                    LearnUserService.Add(e.XSenderID, e.Name, e.Password);
                }, true);

            work.Command<LearnUserLogin>(
                c =>
                {
                    if (!LearnUserService.Has(c.Name, c.Password))
                        throw new Exception("该用户不存在");


                    var userID = (from p in VM.Users where p.Name == c.Name && p.Password == c.Password select p.ID).Single();
                    var tokenID = (from p in VM.Tokens where p.EntityID == userID select p.ID).Single();

                    var token = new Token(tokenID);
                    var ticket = token.Login(c.Channel);

                    c.SetResult(ticket);
                });
        }
    }

    public class CreateLearnUser : XCommand
    {
        public string Name { get; set; }
        public string Password { get; set; }
    }

    public class LearnUserLogin : XCommand
    {
        public string Name { get; set; }
        public string Password { get; set; }

        public Token.Channel Channel { get; set; }
    }
}